package com.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.BuildDao;
import com.model.Build;
import com.model.PageBean;
import com.util.DbUtil;
import com.util.StringUtil;

/**
 * @author wangjg
 * @date 2023/11/1 15:15
 * @Description: 楼宇管理servlet
 */
@WebServlet(name = "DormBuildServlet")
public class BuildServlet extends HttpServlet {
    DbUtil dbUtil = new DbUtil();
    BuildDao buildDao = new BuildDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Object currentUserType = session.getAttribute("currentUserType");
        String searchText = request.getParameter("searchText");
        String searchType = request.getParameter("searchType");
        String action = request.getParameter("action");
        String page = request.getParameter("page");
        if(StringUtil.isEmpty(page)){
            page = "0";
        }
        Build build = new Build();
        if("preSave".equals(action)) {
            buildPreSave(request, response);
            return;
        } else if("save".equals(action)){
            buildSave(request, response);
            return;
        } else if("delete".equals(action)){
            buildDelete(request, response);
            return;
        } else if("list".equals(action)) {
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    build.setName(searchText);
                } else if("num".equals(searchType)) {
                    build.setNum(searchText);
                }
            }
            session.removeAttribute("searchText");
            session.removeAttribute("searchType");
            request.setAttribute("searchText", searchText);
            request.setAttribute("searchType", searchType);
        } else if("search".equals(action)){
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    build.setName(searchText);
                } else if("num".equals(searchType)) {
                    build.setNum(searchText);
                }
                session.setAttribute("searchText", searchText);
                session.setAttribute("searchType", searchType);
            } else {
                session.removeAttribute("searchText");
                session.removeAttribute("searchType");
            }
        }
        Connection con = null;
        PageBean pageBean = new PageBean(Integer.parseInt(page), 5);
        request.setAttribute("pageSize", pageBean.getPageSize());
        request.setAttribute("page", pageBean.getPage());
        try {
            con=dbUtil.getCon();
            if("admin".equals(currentUserType)) {
                List<Build> buildList = buildDao.buildList(con, pageBean,build);
                int total = buildDao.buildCount(con, build);
                String pageCode = this.genPage(total, Integer.parseInt(page),5);
                request.setAttribute("pageCode", pageCode);
                request.setAttribute("buildList", buildList);
                request.setAttribute("mainPage", "admin/build.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void buildDelete(HttpServletRequest request,
                              HttpServletResponse response) {
        String buildId = request.getParameter("buildId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            buildDao.deleteBuild(con,buildId);
            request.getRequestDispatcher("build?action=list").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void buildSave(HttpServletRequest request,
                            HttpServletResponse response)throws ServletException, IOException {
        String buildId = request.getParameter("buildId");
        String name = request.getParameter("name");
        String num = request.getParameter("num");
        String detail = request.getParameter("detail");
        Build build;
        if(StringUtil.isNotEmpty(buildId)){
            build = new Build(Integer.parseInt(buildId),name, num, detail);
        }else {
            build = new Build(null,name, num, detail);
        }
        Connection con = null;
        try {
            con = dbUtil.getCon();
            int saveNum = 0;
            if(StringUtil.isNotEmpty(buildId) ) {
                saveNum = buildDao.updateBuild(con, build);
            } else {
                saveNum = buildDao.addBuild(con, build);
            }
            if(saveNum > 0) {
                request.getRequestDispatcher("build?action=list").forward(request, response);
            } else {
                request.setAttribute("build", build);
                request.setAttribute("error", "保存失败");
                request.setAttribute("mainPage", "admin/buildSave.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void buildPreSave(HttpServletRequest request,
                               HttpServletResponse response)throws ServletException, IOException {
        String buildId = request.getParameter("buildId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            if (StringUtil.isNotEmpty(buildId)) {
                Build build = buildDao.buildInfo(con, Integer.parseInt(buildId));
                request.setAttribute("build", build);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        request.setAttribute("mainPage", "admin/buildSave.jsp");
        request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
    }

    private String genPage(int totalNum, int currentPage, int pageSize){
        int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuilder pageCode = new StringBuilder();
        pageCode.append("<li><a href='build?page=1'>首页</a></li>");
        if(currentPage==1) {
            pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
        }else {
            pageCode.append("<li><a href='build?page=").append(currentPage - 1).append("'>上一页</a></li>");
        }
        for(int i=currentPage-2;i<=currentPage+2;i++) {
            if(i<1||i>totalPage) {
                continue;
            }
            if(i==currentPage) {
                pageCode.append("<li class='active'><a href='#'>").append(i).append("</a></li>");
            } else {
                pageCode.append("<li><a href='build?page=").append(i).append("'>").append(i).append("</a></li>");
            }
        }
        if(currentPage==totalPage) {
            pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
        } else {
            pageCode.append("<li><a href='build?page=").append(currentPage + 1).append("'>下一页</a></li>");
        }
        pageCode.append("<li><a href='build?page=").append(totalPage).append("'>尾页</a></li>");
        return pageCode.toString();
    }
}
